/*
 * BanBu_ManuscriptViewController
 * @description 本文件提供对话中的收藏界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供对话中的收藏界面的ViewController
 */

#import "BanBu_ManuscriptViewController.h"
#import "BanBu_ThemeManager.h"
#import "SVSegmentedControl.h"
#import "BanBu_ManuscriptTableViewCell.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBuAPIs.h"
#import "BanBu_SmileViewAPI.h"
#import "BanBu_EditTextViewController.h"
#import "BanBu_ChatViewController.h"
#import "BanBu_EmoManger.h"
#import "BanBu_VoiceView.h"

@interface BanBu_ManuscriptViewController ()

@end

@implementation BanBu_ManuscriptViewController
@synthesize manuscriptArray= _manuscriptArray;

-(void)dealloc
{
    [_voiceView release];
    _voiceView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    MyAppDataManager.manuscriptController = nil;
    [_tableView release],_tableView = nil;
    [_deletDic release],_deletDic = nil;
    [_selectedArray release],_selectedArray = nil;
    [_manuscriptArray release],_manuscriptArray = nil;
    
    [_deleteView release];
    [_addContentView release];
    
    [_addBtn release];
    [_selectIndexPath release];
    [super dealloc];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _manuscriptArray = [[NSMutableArray alloc]initWithCapacity:30];
    MyAppDataManager.manuscriptController = self;
    [_deleteCollectBu setTitle:NSLocalizedString(@"deleteButton", 删除) forState:UIControlStateNormal];
    //    if(segmentController)
    //    {
    //        [segmentController release];
    //    }
    //    segmentController = [[AKSegmentedControl alloc] initWithFrame:CGRectMake(5,5,196,34)];
    //    [segmentController setDelegate:self];
    //    [self setupSegmentedControl];
    
    self.title= NSLocalizedString(@"collectionButton", nil);
    
    [self createDeleteButton];
    
    //初始化tableView
    [self setupTableView];
    
    self.deletDic = [[[NSMutableDictionary alloc]initWithCapacity:8] autorelease];
    self.selectedArray = [[[NSMutableArray alloc]initWithCapacity:8] autorelease];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableView:) name:KFinishDownloadingAmsg object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadViewStop) name:KNoRefreshCollectAmsg object:nil];
    //初始化：添加、删除
    [self setupAddAndDeleteView];
}

- (void)loadViewStop
{
    [loadingView stopAnimating];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createDeleteButton
{
    //添加“删除”按钮
    deleteButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    deleteButton.position = ButtonPositionRight;
    CGFloat btnLen1 = [NSLocalizedString(@"deleteButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
    [deleteButton setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
    deleteButton.tag = 101;
    [deleteButton addTarget:self action:@selector(editTable) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:deleteButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
}

//设置分段控件
- (void)setupSegmentedControl
{
    NSArray *titleArr = [NSArray arrayWithObjects:NSLocalizedString(@"manuscriptTitle", nil),NSLocalizedString(@"systemTitle", nil), nil];
    UIImage *backgroundImage = [ThemeManager getThemeImage:@"segmentTitle.png"];//[[ThemeManager getThemeImage:@"segmentTitle.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)];
    
    [segmentController setBackgroundImage:backgroundImage];
    [segmentController setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin];
    
    UIImage *buttonBackgroundImagePressed_left = [UIImage imageNamed:@"segmented-bg-pressed_left.png"];
    UIImage *buttonBackgroundImagePressed_right = [UIImage imageNamed:@"segmented-bg-pressed_right.png"];
    
    //对话Button
    UIButton *buttonTalk = [[[UIButton alloc] init] autorelease];
    [buttonTalk setTitle:[titleArr objectAtIndex:0] forState:UIControlStateNormal];
    [buttonTalk setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonTalk.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0]];
    
    [buttonTalk setBackgroundImage:buttonBackgroundImagePressed_left forState:UIControlStateHighlighted];
    [buttonTalk setBackgroundImage:buttonBackgroundImagePressed_left forState:UIControlStateSelected];
    [buttonTalk setBackgroundImage:buttonBackgroundImagePressed_left forState:(UIControlStateHighlighted|UIControlStateSelected)];
    
    UIImageView *lineview1 = [[UIImageView alloc] initWithFrame:CGRectMake(segmentController.frame.size.width/2, 0, 1, segmentController.frame.size.height)];
    //    lineview1.image = [UIImage imageNamed:@"segmented-separator.png"];
    [buttonTalk addSubview:lineview1];
    [lineview1 release];
    
    // 来访记录Button
    UIButton *buttonVisit = [[[UIButton alloc] init] autorelease];
    
    [buttonVisit setTitle:[titleArr objectAtIndex:1] forState:UIControlStateNormal];
    [buttonVisit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonVisit.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0]];
    [buttonVisit setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 5.0, 0.0, 0.0)];
    
    [buttonVisit setBackgroundImage:buttonBackgroundImagePressed_right forState:UIControlStateHighlighted];
    [buttonVisit setBackgroundImage:buttonBackgroundImagePressed_right forState:UIControlStateSelected];
    [buttonVisit setBackgroundImage:buttonBackgroundImagePressed_right forState:(UIControlStateHighlighted|UIControlStateSelected)];
    
    
    [segmentController setButtonsArray:@[buttonTalk, buttonVisit]];
    
    [self.navigationItem.titleView.superview bringSubviewToFront:self.navigationItem.titleView];
    self.navigationItem.titleView = segmentController;
}


#pragma mark - 初始化table
//比较，排序
NSComparisonResult compareWithFavid(NSDictionary *firstDict, NSDictionary *secondDict, void *context)
{
    NSString * first = [firstDict valueForKey:KeyFavid];
    NSString * second = [secondDict valueForKey:KeyFavid];
    
    //    if (strcmp([first UTF8String], [second UTF8String])<0)
    //    {
    //        return NSOrderedAscending;
    //    }
    //    else if(strcmp([first UTF8String], [second UTF8String])>0)
    //    {
    //        return NSOrderedDescending;
    //    }
    if (strcmp([first UTF8String], [second UTF8String])<0)
    {
        return NSOrderedDescending;
    }
    else if(strcmp([first UTF8String], [second UTF8String])>0)
    {
        return NSOrderedAscending;
    }
    else
    {
        return NSOrderedSame;
    }
}

#pragma mark - 获取本地存储的收藏数据
//获取数据
-(void)getManuscriptData
{
    //先判断缓存数据是否过期
    BOOL flag = [BanBu_CommUtils needUpdateCache:CollectTimeKey timeInterval:CollectTimeInterval];
    //已经过期
    if (flag)
    {
        return;
    }
    //获取数据源,修改2014/07/16
    NSDictionary * collectedAmsgDic = [BanBu_CommUtils getLocalData:CollectDataKey];
    //    NSMutableDictionary * collectedAmsgDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectedAmsgInfoPath]];
    //    NSMutableDictionary * collectedAmsgDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectedAmsgInfoPath]];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:collectedAmsgDic.allValues];
    
    [array sortUsingFunction:compareWithFavid context:NULL];
    
    [self.manuscriptArray removeAllObjects];
    [self.manuscriptArray addObjectsFromArray:array];
    
    [array release];
}

#pragma mark - 初始化tableview，获取本地存储收藏数据
-(void)setupTableView
{
    //获取数据源
    [self getManuscriptData];
    //2014/07/16添加，判断本地是否已下载收藏
    //self.manuscriptArray.count = 0，未下载或未收藏，重新请求一次数据
    if (self.manuscriptArray.count == 0)
    {
        //下载收藏的信息
        NSMutableDictionary *loginDic = [NSMutableDictionary dictionaryWithCapacity:8];
        [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
        //请求第一页收藏数据,2014/07/17
        [loginDic setValue:@"1" forKeyPath:@"pageno"];
        [AppComManager getBanBuDataWIthCollectEmo:BanBu_GetCollectAmsg_ByUser par:loginDic delegate:MyAppDataManager];
    }
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44) style:UITableViewStylePlain];
    self.tableView = tableView;
    
    [self.view addSubview:tableView];
    [tableView release];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    
    UIView * moreView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)] autorelease];
    
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.hidden = NO;
    [loadingView setHidesWhenStopped:YES];
    loadingView.frame = CGRectMake(0, 0, 50, 50);
    loadingView.center = CGPointMake(160, 20);
    moreView.backgroundColor = [UIColor clearColor];
    [moreView addSubview:loadingView];
    [loadingView release];
    self.tableView.tableFooterView = moreView;
}

-(void)setupAddAndDeleteView
{
    //添加收藏的View
    [self.view bringSubviewToFront:self.addContentView];
    [self.view bringSubviewToFront:self.addBtn];
    
    if (__MainScreen_Height<500)
    {
        CGRect frame = self.addBtn.frame;
        frame.origin.y = 340;
        self.addBtn.frame = frame;
        
        
        frame = self.addContentView.frame;
        frame.origin.y = 265;
        self.addContentView.frame = frame;
        
        frame = self.deleteView.frame;
        frame.origin.y = 367;
        self.deleteView.frame = frame;
    }
    
    //初始化删除View
    self.deleteView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btn_manuscrip_deletebg.png"]];
    
    [self.view bringSubviewToFront:self.deleteView];
}

#pragma mark - 点击navigationbar右上角删除或取消按钮
-(void)editTable
{
    [self setEditing:!self.tableView.editing animated:YES];
}

//修改tableView可编辑状态
- (void)setEditing:(BOOL)editting animated:(BOOL)animated
{
    self.tableView.editing = !self.tableView.editing;
	[super setEditing:!self.editing animated:YES];
    if(self.tableView.editing)
    {
        //删除状态，下面要显示删除view，tableview上移
        [self.tableView setFrame:CGRectMake(0, 0, 320, __MainScreen_Height - 93)];
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"cancelNotice", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+30, 30);
        [deleteButton setImage:nil forState:UIControlStateNormal];
        [deleteButton setTitle:NSLocalizedString(@"cancelNotice", nil) forState:UIControlStateNormal];
        
        [self.deletDic removeAllObjects];
        self.deleteView.hidden = NO;
        
        self.addContentView.hidden = YES;
        [self.addBtn setImage:[UIImage imageNamed:@"btn_manuscrip_add.png"] forState:UIControlStateNormal];
        self.addBtn.selected = !self.addBtn.selected;
        self.addBtn.hidden = YES;
    }
    else
    {
        //取消删除状态，tableview恢复原来frame
        [self.tableView setFrame:CGRectMake(0, 0, 320, __MainScreen_Height - 44)];
        CGFloat btnLen1 = [NSLocalizedString(@"deleteButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        [deleteButton setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
        
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        self.addBtn.hidden = NO;
        [self.deletDic removeAllObjects];
        self.deleteView.hidden = YES;
    }
}

//刷新table
-(void)reloadTableView:(NSNotification *)notifi
{
    //已经加载完数据
    _isLoading = NO;
    [loadingView stopAnimating];
    //获取数据源
    [self getManuscriptData];
    
    [self.tableView reloadData];
}


#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.manuscriptArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"manuscriptCell";
    
    BanBu_ManuscriptTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil)
    {
        NSArray * objects = [[NSBundle mainBundle]loadNibNamed:@"BanBu_ManuscriptTableViewCell" owner:nil options:nil];
        
        for (id object in objects)
        {
            if ([object isKindOfClass:[BanBu_ManuscriptTableViewCell class]])
            {
                cell = (BanBu_ManuscriptTableViewCell *)object;
                break;
            }
        }
        
        cell.backgroundColor = [UIColor clearColor];
        [cell setBg];
        cell.mediaView.appChatController = _appChatController;
    }
    
    NSDictionary * amsg = [_manuscriptArray objectAtIndex:indexPath.row];
    //设置cell的各属性
    [cell setCellInfo:amsg withEditing:tableView.editing];
    
    //2014/07/17添加，解决cell重用出现的显示selected错误问题
    NSString * favid = [amsg valueForKey:KeyFavid];
    if ([self.deletDic valueForKey:favid])
    {
        [cell setChecked:YES];
    }
    else
    {
        [cell setChecked:NO];
    }
    return cell;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.editing)
    {
        NSMutableDictionary *talkPeopleDic = [NSMutableDictionary dictionaryWithDictionary:[self.manuscriptArray objectAtIndex:indexPath.row]];
        BOOL isChecked = [[talkPeopleDic valueForKey:@"isChecked"] boolValue];
        
        [talkPeopleDic setValue:[NSString stringWithFormat:@"%d",!isChecked] forKey:@"isChecked"];
        
        NSString * favid = [talkPeopleDic valueForKey:KeyFavid];
        
        [self.manuscriptArray replaceObjectAtIndex:indexPath.row withObject:talkPeopleDic];
        
        BanBu_ManuscriptTableViewCell *cell = (BanBu_ManuscriptTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell setChecked:!isChecked];
        if(!isChecked)
        {
            [self.deletDic setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:favid];
        }
        else
        {
            [self.deletDic removeObjectForKey:favid];
        }
    }
    else//发送消息
    {
        _selectedRow = indexPath.row;
        self.selectIndexPath = indexPath;
        
        NSDictionary * amsg = [self.manuscriptArray objectAtIndex:indexPath.row];
        UIActionSheet * sendSheet = nil;
        
        if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeText)
        {
            sendSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil),NSLocalizedString(@"editAndSend", nil), nil];
        }
        else if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeImage)
        {
            sendSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil),NSLocalizedString(@"previewBigImage", nil), nil];
        }
        else if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeVoice)
        {
            BanBu_ManuscriptTableViewCell * cell = (BanBu_ManuscriptTableViewCell *)[self.tableView cellForRowAtIndexPath:_selectIndexPath];
            
            if (cell.voiceView.playingView)
            {
                sendSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil),NSLocalizedString(@"auditionStop", nil), nil];
            }
            else
            {
                sendSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil),NSLocalizedString(@"auditionVoice", nil), nil];
            }
        }
        
        [sendSheet showInView:self.view];
        [sendSheet release];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark - 收藏加载更多

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //编辑状态时不加载更多
    if (self.tableView.editing)
    {
        return;
    }
    if (self.tableView.contentOffset.y + self.tableView.frame.size.height - self.tableView.contentSize.height > 30)
    {
        [self collectClickMore];
    }
    //    if ((self.tableView.contentOffset.y + self.tableView.frame.size.height - self.tableView.contentSize.height > 30)&&(self.tableView.contentSize.height > __MainScreen_Height)) {
    //        [self collectClickMore];
    //    }
}

- (void)collectClickMore
{
    //当前没有正在加载，并且存在更多数据
    if (!_isLoading)
    {
        [loadingView startAnimating];
        //下载收藏的信息
        NSMutableDictionary *loginDic = [NSMutableDictionary dictionaryWithCapacity:8];
        [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
        //重新请求第一页收藏的数据,2014/07/17
        NSLog(@"%d",[[BanBu_CommUtils getLocalData:CollectPageKey] intValue]);
        NSString * pageNo = [NSString stringWithFormat:@"%d",[[BanBu_CommUtils getLocalData:CollectPageKey] intValue] + 1];
        [loginDic setValue:pageNo forKeyPath:@"pageno"];
        [AppComManager getBanBuDataWIthCollectEmo:BanBu_GetCollectAmsg_ByUser par:loginDic delegate:MyAppDataManager];
        _isLoading=YES;
        
    }
    
}
#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0://直接发送
        {
            NSDictionary * amsg = [_manuscriptArray objectAtIndex:_selectedRow];
            NSMutableDictionary * sendDic = [NSMutableDictionary dictionaryWithCapacity:8];
            
            if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeText)// 发送文本
            {
                [sendDic setValue:[amsg valueForKey:KeyContent] forKey:KeyContent];
                [sendDic setValue:[NSNumber numberWithInt:ChatCellTypeText] forKey:KeyType];
                [sendDic setValue:@"mo" forKey:KeyShowFrom];
            }
            else if([[amsg valueForKey:KeyType] integerValue] == MsgTypeImage)// 发送图片
            {
                NSString * imageString = [amsg valueForKey:KeyContent];
                [sendDic setValue:imageString forKey:@"image"];
                
                NSArray *suffixArr = [[NSArray alloc]initWithArray:[imageString componentsSeparatedByString:@"."]];
                [sendDic setValue:[suffixArr lastObject] forKey:@"filetype"];
                [sendDic setValue:[NSNumber numberWithInt:ChatCellTypeImage] forKey:KeyType];
                [sendDic setValue:@"collect" forKey:KeyShowFrom];
            }
            else if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeVoice)// 发送语音
            {
                [sendDic setValue:[amsg valueForKey:KeyContent] forKey:@"music"];
                [sendDic setValue:[NSNumber numberWithInt:ChatCellTypeVoice] forKey:KeyType];
                [sendDic setValue:@"collect" forKey:KeyShowFrom];
            }
            
            //发送消息
            [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
            
            //popToChat
            [self.navigationController popToViewController:_appChatController animated:YES];
        }
            break;
        case 1://编辑内容
        {
            NSDictionary * amsg = [_manuscriptArray objectAtIndex:_selectedRow];
            if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeText)//编辑文本
            {
                BanBu_EditTextViewController * editText = [[BanBu_EditTextViewController alloc]init];
                editText.inputString = [amsg valueForKey:KeyContent];
                editText.manuscriptDic = amsg;
                editText.appChatController = self.appChatController;
                [self.navigationController pushViewController:editText animated:YES];
                [editText release];
            }
            else if([[amsg valueForKey:KeyType] integerValue] == MsgTypeImage)// 预览图片
            {
                BanBu_ManuscriptTableViewCell * cell = (BanBu_ManuscriptTableViewCell *)[self.tableView cellForRowAtIndexPath:_selectIndexPath];
                [cell.mediaView btnAction:nil];
            }
            else if ([[amsg valueForKey:KeyType] integerValue] == MsgTypeVoice)// 试听语音
            {
                BanBu_ManuscriptTableViewCell * cell = (BanBu_ManuscriptTableViewCell *)[self.tableView cellForRowAtIndexPath:_selectIndexPath];
                
                if (cell.voiceView.playingView)
                {
                    [cell.voiceView stopPlaying:nil];
                }
                else
                {
                    [cell.voiceView btnAction:cell.voiceView.showButton];
                }
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 删除选中的收藏
- (IBAction)deleteAmsg:(UIButton *)sender
{
    //tableview恢复原来的frame
    [self.tableView setFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44)];
    if(self.deletDic.count)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"deleteNotice", nil) activityAnimated:YES];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            NSMutableDictionary * deleteDic = [NSMutableDictionary dictionaryWithCapacity:8];
            [deleteDic setValue:[self.deletDic.allKeys componentsJoinedByString:@","] forKey:@"favidlist"];
            
            //提交删除的数据
            [AppComManager getBanBuData:BanBu_DelCollectAmsg_ByUser par:deleteDic delegate:MyAppDataManager];
            
            NSMutableArray * indexPathArray = [NSMutableArray arrayWithCapacity:20];
            
            for (NSNumber * row in self.deletDic.allValues)
            {
                NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[row integerValue] inSection:0];
                
                [indexPathArray addObject:indexPath];
            }
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                //数据源删除
                
                NSDictionary * collectedDic = [BanBu_CommUtils getLocalData:CollectDataKey];
                
                NSMutableDictionary * collectedAmsgDic = [[NSMutableDictionary alloc]initWithDictionary:collectedDic];
                [collectedAmsgDic removeObjectsForKeys:self.deletDic.allKeys];
                [BanBu_CommUtils setLocalData:collectedAmsgDic key:CollectDataKey];
                [collectedAmsgDic release];
                
                //获取数据源
                [self getManuscriptData];
                
                //界面删除
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
                [self.tableView endUpdates];
                
                
                //删除完成后隐藏删除按钮
                [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0.0];
                
                CGFloat btnLen1 = [NSLocalizedString(@"deleteButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
                deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
                [deleteButton setTitle:NSLocalizedString(@"deleteButton", nil) forState:UIControlStateNormal];
                
                //为了使用多语言环境，改变文本显示时，要调整按钮长度
                [self.deletDic removeAllObjects];
                self.deleteView.hidden = YES;
                [self.addBtn setHidden:NO];
                self.tableView.editing = NO;
            });
        });
    }
}



#pragma mark - 添加收藏
- (IBAction)addAmsgBtn:(UIButton *)sender
{
    self.addBtn.selected = !self.addBtn.selected;
    
    if (self.addBtn.selected)
    {
        [self.addBtn setBackgroundImage:[UIImage imageNamed:@"btn_manuscrip_add_rall.png"] forState:UIControlStateNormal];
        self.addContentView.hidden = NO;
    }
    else
    {
        [self.addBtn setBackgroundImage:[UIImage imageNamed:@"btn_manuscrip_add.png"] forState:UIControlStateNormal];
        self.addContentView.hidden = YES;
    }
}

#pragma mark - 添加文本
-(IBAction)addActionText:(UIButton *)sender
{
    BanBu_EditTextViewController * editText = [[BanBu_EditTextViewController alloc]init];
    editText.inputString = @"";
    editText.manuscriptDic = nil;
    editText.appChatController = self.appChatController;
    [self.navigationController pushViewController:editText animated:YES];
    [editText release];
    [self addAmsgBtn:self.addBtn];
}

#pragma mark - 添加图片
//添加图片
-(IBAction)addActionImage:(UIButton *)sender
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [picker setAllowsEditing:YES];
    [self presentViewController:picker animated:YES];
    [picker release];
    [self addAmsgBtn:self.addBtn];
}

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo
{
    //图片的路径，判断重复
    NSString * imageUrl = [NSString stringWithFormat:@"%@",[editingInfo valueForKey:UIImagePickerControllerReferenceURL]];
    for (NSDictionary * collectDict in _manuscriptArray)
    {
        NSLog(@"%@",collectDict);
        if ([[collectDict valueForKey:KeyLocalUrl] isEqualToString:imageUrl])
        {
            [picker dismissModalViewControllerAnimated:YES];
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"re_collect", nil) activityAnimated:NO duration:2.2f];
            return;
        }
    }
    
    
    //获取图片然后上传
    NSData *imageData = nil;
    
    if (image.size.width>1500 || image.size.height>1500)
    {
        image = [MyAppDataManager scaleImage:image proportion:3];
    }
    else if (image.size.width>1000 || image.size.height > 1000)
    {
        image = [MyAppDataManager scaleImage:image proportion:2];
    }
    
    imageData = UIImageJPEGRepresentation(image, 0.7);
    if(imageData.length>100*1024)
    {
        NSData * date1 = nil;
        date1 = UIImageJPEGRepresentation(image, 0.6);
        imageData = date1;
    }
    
    //
    NSMutableDictionary * parDic = [NSMutableDictionary dictionaryWithCapacity:8];
    
    [parDic setValue:[NSNumber numberWithInt:MsgTypeImage] forKey:KeyType];
    [parDic setValue:MyAppDataManager.chatuid forKey:KeyFromUidTalk];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * collectedTime = [formatter stringFromDate:[NSDate date]];
    
    [parDic setValue:collectedTime forKey:KeyCollectAmsgTime];
    [parDic setValue:collectedTime forKey:KeyContent];
    //2014年08月19日11:40:53,添加url，防止重复收藏
    [parDic setValue:imageUrl forKey:KeyLocalUrl];
    self.navigationController.view.userInteractionEnabled = NO;
    //将图片上传到服务器
    [AppComManager uploadCollectedEmo:imageData mediaName:[NSString stringWithFormat:@"%@.jpg",collectedTime] par:parDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"uploading", nil) activityAnimated:YES];
    [picker dismissViewControllerAnimated:YES];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //取消获取图片
    [picker dismissViewControllerAnimated:YES];
}

#pragma mark - 初始化录音界面

- (void)initVoiceView
{
    _voiceView = [[UIImageView alloc]initWithFrame:CGRectMake(0, (__MainScreen_Height - 455)/2.0, 320, 425)];
    _voiceView.userInteractionEnabled = YES;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"collectVoiceBack" ofType:@"png"];
    _voiceView.image =  [UIImage imageWithContentsOfFile:path];
    
    UIButton * voiceBu = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBu setFrame:CGRectMake(91, 119, 135, 139)];
    NSString *Bupath = [[NSBundle mainBundle] pathForResource:@"collectVoiceBu" ofType:@"png"];
    [voiceBu setImage:[UIImage imageWithContentsOfFile:Bupath] forState:UIControlStateNormal];
    [voiceBu addTarget:self action:@selector(voiceTap) forControlEvents:UIControlEventTouchUpInside];
    [_voiceView addSubview:voiceBu];

    //录音时长按
    UILongPressGestureRecognizer *aLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(record:)];
    [voiceBu addGestureRecognizer:aLongPress];
    [aLongPress release];
    UIButton * cancleBu = [UIButton buttonWithType:UIButtonTypeCustom];
    NSString *canclepath = [[NSBundle mainBundle] pathForResource:@"collectVoiceCancle" ofType:@"png"];
    [cancleBu setImage:[UIImage imageWithContentsOfFile:canclepath] forState:UIControlStateNormal];
    [cancleBu setFrame:CGRectMake(247, 40, 40, 41)];
    [_voiceView addSubview:cancleBu];
    [cancleBu addTarget:self action:@selector(cancleRecord) forControlEvents:UIControlEventTouchUpInside];
    UILabel * voiceLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 267, 220, 20)];
    voiceLabel.backgroundColor = [UIColor clearColor];
    voiceLabel.textColor = [UIColor whiteColor];
    voiceLabel.font = [UIFont boldSystemFontOfSize:14.0];
    voiceLabel.text = NSLocalizedString(@"timeshortNoticte", nil);
    voiceLabel.textAlignment = kTextAlignmentCenter;
    [_voiceView addSubview:voiceLabel];
    [voiceLabel release];

}
//弹出语音录制时间过短提示
-(void)voiceTap
{
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"timeshortNoticte", nil) activityAnimated:NO duration:1.0];
}

- (void)cancleRecord
{
    [_voiceView removeFromSuperview];
}
#pragma mark - 添加语音
//添加语音
-(IBAction)addActionVoice:(UIButton *)sender
{
    if (!_voiceView)
    {
        [self initVoiceView];
    }
    [self.view addSubview:_voiceView];
    [self addAmsgBtn:self.addBtn];
    return;
    
}




- (void)record:(UILongPressGestureRecognizer *)longPress
{
    [self.view endEditing:YES];
    UIButton *button = (UIButton *)longPress.view;
    if(button.selected)
    {
        CGPoint point = [longPress locationInView:_recordView];
        if(longPress.state == UIGestureRecognizerStateEnded)
        {
            button.selected = NO;
            [_recordView touchesEndInView:point];
            _recordView = nil;
        }
        else
            [_recordView touchesMovedInView:point];
        
        return;
    }
    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        button.selected = YES;
        RecordView *recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height)];
        if (IS_IOS_7)
        {
            recordView.frame = CGRectMake(0, 20, 320, __MainScreen_Height);
        }
        _recordView = recordView;
        NSString *fileName = @"collectSound.amr";
        NSString * audioPath = [AppComManager pathForMsgMedia:fileName];
        //如果存在文件，说明是重录，删除之前文件
        if ([FileManager fileExistsAtPath:audioPath])
        {
            [FileManager removeItemAtPath:audioPath error:nil];
        }
        _recordView.audioPath = audioPath;
        recordView.delegate = self;
        [self.navigationController.view addSubview:recordView];
        [recordView release];
    }
}

#pragma mark - 录音结束
/**
 * @函数名称：recordView:recordDidCompleted:recordTime:
 * @函数描述：录音结束，获取录音数据和录音时间长度
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)recordView:(RecordView *)recordView recordDidCompleted:(NSData *)audioData recordTime:(int)duration
{
    if (_voiceView)
    {
        __block UIImageView * bvoiceView = _voiceView;
        [UIView animateWithDuration:1.0 animations:^{
            [bvoiceView removeFromSuperview];
        }];
    }
    if([audioData length] < 100)
    {
        return;
    }
    NSMutableDictionary *parDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [parDic setValue:@"amr" forKey:@"extname"];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * collectedTime = [formatter stringFromDate:[NSDate date]];
    [parDic setValue:collectedTime forKey:KeyCollectAmsgTime];
    [parDic setValue:[NSNumber numberWithInt:MsgTypeVoice] forKey:KeyType];
    [parDic setValue:MyAppDataManager.useruid forKey:KeyFromUidTalk];
    
    //上传语音文件
    [AppComManager uploadCollectedEmo:audioData mediaName:[NSString stringWithFormat:@"%@.amr",collectedTime] par:parDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"uploading", nil) activityAnimated:YES];
    
    NSString *fileName = @"collectSound.amr";
    NSString * audioPath = [AppComManager pathForMsgMedia:fileName];
    //上传之前删除文件
    if ([FileManager fileExistsAtPath:audioPath])
    {
        [FileManager removeItemAtPath:audioPath error:nil];
    }
}


- (void)banbuUploadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"uploadFailNotice", nil) activityAnimated:NO duration:2.0];
        return;
    }
    //    //NSLog(@"%@",resDic);
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        if ([AppComManager respondsDic:resDic isFunctionData:BanBu_AddFavFile_ByPost])//上传图片、语音后
        {
            //            NSLog(@"resDic:%@",resDic);
            NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithCapacity:8];
            [amsg setValue:[resDic valueForKey:@"fileurl"] forKey:KeyContent];
            [amsg setValue:[resDic valueForKey:KeyCollectAmsgTime] forKey:KeyCollectAmsgTime];
            [amsg setValue:[resDic valueForKey:KeyType] forKey:KeyType];
            [amsg setValue:[resDic valueForKey:KeyFromUidTalk] forKey:KeyFromUidTalk];
            [amsg setValue:[resDic valueForKey:KeyLocalUrl] forKey:KeyLocalUrl];
            [self saveToManuscript:amsg];
        }
    }
}

//收藏到草稿
-(void)saveToManuscript:(NSDictionary *)amsg
{
    //收藏
    NSMutableDictionary * parDic = [NSMutableDictionary dictionaryWithCapacity:8];
    
    [parDic setValue:[amsg valueForKey:KeyContent] forKey:KeyContent];
    if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeVoice)
    {
        [parDic setValue:[NSNumber numberWithInt:MsgTypeVoice] forKey:KeyType];
    }
    else
    {
        [parDic setValue:[amsg valueForKey:KeyType] forKey:KeyType];
    }
    
    [parDic setValue:MyAppDataManager.chatuid forKey:KeyFromUidTalk];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * collectedTime = [formatter stringFromDate:[NSDate date]];
    
    [parDic setValue:collectedTime forKey:KeyCollectAmsgTime];
    [parDic setValue:[amsg valueForKey:KeyLocalUrl] forKey:KeyLocalUrl];
    //提交服务器
    [AppComManager getBanBuDataWIthCollectEmo:BanBu_AddCollectAmsg_ByUser par:parDic delegate:MyAppDataManager];
    
    if([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeImage)//收藏的是图片
    {    //收藏图片是要把图片转存到收藏草稿的文件夹ManuscriptFolder
        NSString * newFilePath = [AppComManager pathForCollectImage:ManuscriptFolder];
        NSString * olderFilePath = [AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]];
        
        //拷贝文件到收藏文件夹
        [FileManager copyItemAtPath:olderFilePath toPath:newFilePath error:nil];
    }
    else if([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeVoice)//收藏的是语音
    {    //收藏图片是要把图片转存到收藏草稿的文件夹ManuscriptFolder
        NSString * newFilePath = [AppComManager pathForCollectImage:ManuscriptFolder];
        NSString * olderFilePath = [AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]];
        
        //拷贝文件到收藏文件夹
        [FileManager copyItemAtPath:olderFilePath toPath:newFilePath error:nil];
    }
}

@end




